<template>
  <el-card>
    <el-row>
      <el-button type="primary" @click="handleadd">新增</el-button>
      <el-button type="danger" style="margin-right: 10px" @click="handleDelList">批量删除</el-button>
      <el-input v-model="data.search" placeholder="用户名" style="width: 200px; margin-right: 10px">
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="warning" @click="handleEmpty">清空</el-button>
    </el-row>

    <el-table
        v-loading="data.loading === true"
        :data="data.tableData"
              v-if="data.tableData.length > 0"
              style="width: 100%;margin-top: 10px; overflow: hidden"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" sortable min-width="50"></el-table-column>
      <el-table-column prop="id" label="序号" sortable :sort-method="sortById" min-width="100"></el-table-column>
      <el-table-column prop="username" label="用户名" min-width="100" sortable></el-table-column>
      <el-table-column prop="nickname" label="昵称" min-width="150" sortable></el-table-column>
      <!--      <el-table-column prop="avatar" label="头像" width="150" ></el-table-column>-->
      <el-table-column prop="role" label="角色" min-width="150" sortable></el-table-column>
      <el-table-column prop="status" label="状态" min-width="150" sortable></el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="150" sortable></el-table-column>
      <el-table-column prop="mobile" label="手机号" min-width="150" sortable></el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="180" sortable></el-table-column>
      <el-table-column label="操作" min-width="150">
        <template #default="scope">
          <el-button-group>
            <el-button size="default" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-else :image-size="200"></el-empty>
    <div v-if="data.total" style="margin-top: 10px">
      <el-pagination
          background
          small
          :page-size="data.pageSize"
          :current-page="data.pageNum"
          layout="total,prev, pager, next,jumper"
          :total="data.total"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <el-dialog v-model="data.dialogFormVisible" title="用户信息" width="40%" style="font-size: 50px" destroy-on-close>
      <el-form :model="data.form" label-width="120px" style="padding-right: 60px">
        <!--        <el-form-item label="头像" >-->
        <!--          <el-upload :action="BASE_URL+'/api/user/saveAvatar'">-->
        <!--            <el-button type="primary">点击上传</el-button>-->
        <!--          </el-upload>-->
        <!--        </el-form-item>-->
        <el-form-item label="用户名">
          <el-input v-model="data.form.username" autocomplete="off" :disabled="data.nameVis"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="data.form.password" show-password autocomplete="off"/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="data.form.nikename" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="data.form.role" placeholder="选择一个角色">
            <el-option label="普通用户" value="1"/>
            <el-option label="管理员" value="3"/>
            <el-option label="演示" value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <!--          <el-select v-model="data.form.status" placeholder="选择状态">-->
          <!--            <el-option label="正常" value="0" />-->
          <!--            <el-option label="封号" value="1" />-->
          <!--          </el-select>-->
          <el-radio-group v-model="data.form.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">封号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="data.form.email" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="data.form.moblie" autocomplete="off"/>
        </el-form-item>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Formcancel">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import {Search} from "@element-plus/icons-vue";
import {nextTick, onMounted, reactive} from "vue";
import serve from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";


nextTick(() => {
  // Your code that depends on DOM updates
});
const data = reactive({
  tableData: [],
  loading: false,
  total: 0,
  pageNum: 1,
  pageSize: 10,
  form: {
    id: '',
    username: '',
    password: '',
    nikename: '',
    avatar: '',
    role: '',
    status: '',
    email: '',
    moblie: '',
    selectedIds: [],
  },
  search: '',
  dialogFormVisible: false,
  nameVis: false,
})
const Formcancel = () => {
  data.dialogFormVisible = false
  data.nameVis = false
}
const handleadd = () => {
  data.dialogFormVisible = true
  data.form = {}
}


//弹窗保存数据
const save = async () => {
  try {
    if (!data.form.username || !data.form.password) {
      throw new Error
    }
    // console.log(data.form)
    if (data.form.status === 0) {
      data.form.status = '0'
    } else {
      data.form.status = '1'
    }

    const res = await serve.request({
      method: 'post',
      url: data.form.id ? '/user/update' : '/user/create',
      data: data.form
    }).then(async res => {
      // console.log(res)
      if (res.data.code === 200) {
        data.dialogFormVisible = false
        await nextTick(); // 确保 DOM 更新完成
        dataload('/user/list')
        ElMessage.success('成功')
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  } catch (error) {
    console.error('请求错误', error);
    if (error.msg) {
      ElMessage.error(error.msg)
    } else {
      ElMessage.error('请检查输入')
    }

  }
}

const dataload = async (murl) => {
  try {
    const response = await serve.get(murl, {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        keyword: data.search,
      }
    });
    // console.log(response)
    if (response.data.code === 200) {
      data.tableData = response.data.data?.list || []
      data.total = response.data.data.total
    } else {
      console.error('数据加载失败', response.data.msg);
    }
  } catch (error) {
    console.error('请求错误', error);
  }
  data.nameVis = false
}
const handleSearch = () => {
  // console.log(data.search)
  //根据搜索条件查询
  dataload('/user/keyword')
  // try {
  //   const response = await serve.get('/user/keyword',{
  //     params:{
  //       pageNum: data.pageNum,
  //       pageSize:data.pageSize,
  //       keyword:data.search,
  //     }
  //   } );
  //   console.log(response)
  //   if (response.data.code === 200) {
  //     data.tableData = response.data.data.list
  //     data.total = response.data.data.total
  //   } else {
  //     console.error('数据加载失败', response.data.msg);
  //   }
  // } catch (error) {
  //   console.error('请求错误', error);
  // }
}
const handleEmpty = () => {
  data.search = ''
  data.pageNum = 1
  load()
}
const handleCurrentChange = (number) => {
  data.pageNum = number
  load()
}
const sortById = (a, b) => {
  return Number(a.id) - Number(b.id);
};


const load = async () => {
  data.loading=true;
  setTimeout(() => {
    data.loading = false;
  }, 1000);
  await dataload('/user/list')
  await nextTick(); // 确保 DOM 更新完成
  // try {
  //   const response = await serve.get('/user/list',{
  //     params:{
  //       pageNum: data.pageNum,
  //       pageSize:data.pageSize,
  //       search:data.search,
  //     }
  //   } );
  //   console.log(response)
  //   if (response.data.code === 200) {
  //     data.tableData = response.data.data?.list || []
  //     data.total = response.data.data.total
  //   } else {
  //     console.error('数据加载失败', response.data.msg);
  //   }
  // } catch (error) {
  //   console.error('请求错误', error);
  // }
};

onMounted(() => {
  load();

});

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.nameVis = true
  data.form.id = row.id
  data.form.password = ''
  data.dialogFormVisible = true
}

const handleDelete = async (row) => {
  ElMessageBox.confirm("删除后数据无法恢复，确认删除？", "警告", {type: 'warning'}).then(async re => {
    try {
      const response = await serve.delete(`/user/delete/${row.id}`).then(res => {
        if (res.data.code === 200) {
          ElMessage.success('删除成功')
          load()
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    } catch (error) {
      console.error('请求错误', error);
    }
  }).catch(err => {
    console.log(err)
    ElMessage.info('取消');

  })
}

//批量删除
const handleDelList = async () => {
  if (data.selectedIds === undefined||data.selectedIds.length===0) {
    ElMessage.warning('请选择要删除的用户');
    return;
  }

  ElMessageBox.confirm('确认删除选中的用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await serve.request({
        method: 'delete',
        url: '/user/delList',
        data: data.selectedIds
      })
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        await load();
      } else {
        ElMessage.error(response.data.data.msg);
      }
    } catch (error) {
      console.error('请求错误', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    console.log('删除已取消');
  });
};

const handleSelectionChange = (selection) => {
  data.selectedIds = selection.map(item => item.id);
};
</script>
